<template>
  <div ref="materialTabs">
    <div v-if="isEdit">
      <div style="display: flex;justify-content: space-between">
        <div style="color: #EB4B4B">
          注意：查询不到物资时表明PMS还未接收到仓储系统的出库单信息，请确认该物资是否已在PMS系统发起申领或咨询商合仓储系统物资未出库的原因！
        </div>
      </div>
      <div style="margin: 10px 0;display: flex;justify-content: flex-end;align-items: center">
        <el-radio-group v-model="applyType" class="pms-zr-radio" @input="eleSignInput()">
          <el-radio label="0">单项工程设计方案中出库物资</el-radio>
          <el-radio label="1">整体项目设计方案中出库物资</el-radio>
        </el-radio-group>
        <el-button type="primary" class="pms-button-primary" style="margin-left: 10px" @click="designBind">
          按设计方案绑定
        </el-button>
        <el-button v-if="false" type="primary" class="pms-button-primary">导入绑定方案</el-button>
      </div>
    </div>
    <CustomTable
      ref="customTable"
      :column="column"
      :table-data="tableData"
      :table-header="tableHeader"
      :column-arr="columnArr"
      :key-code="keyCode"
      :is-edit="isEdit"
      @selectResource="selectResource"
    />
    <dialog-confirm v-if="visible" :message="message" @changeStatus="changeMsg" />
    <resource-code-and-label ref="resourceModal" v-if="showResLabel" :visible.sync="showResLabel" :table-data="resourceList" :select-item="selectItem" :osAmount="osAmount" :multipleData="multipleData" @save="saveResource"/>
  </div>
</template>

<script>
import CustomTable from '@/views/acceptanceManagement/materialServiceBind/components/customTable.vue'
import {
    batchUpdateAccState,
    confirmProductBindingBefore,
    optionalConfirmProductBindingBefore,
    queryProductInfoList, saveProductBindingData,queryOsDetailIdAndAssetLabelList,
    updateProductBindingDataByDesign
} from '@/api/acceptanceManagement/materialServiceBind'
import { msgInfoEl } from '@/utils'
import DialogConfirm from '@/views/acceptanceManagement/materialServiceBind/components/dialogConfirm.vue'
import ResourceCodeAndLabel from '@/views/acceptanceManagement/materialServiceBind/components/resourceCodeAndLabel.vue'

export default {
    name: 'MaterialTabs',
    components: {
        DialogConfirm,
        CustomTable,
        ResourceCodeAndLabel
    },
    props: {
        prjParams: {
            type: Object,
            default: () => ({})
        },
        tableHeader: {
            type: Array,
            default: () => []
        },
        isEdit: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            applyType: '0',
            tableData: [],
            tableDataOld: [],
            column: [
                { label: '物料编码', width: '170', prop: 'categoryCode' },
                { label: '物料名称', width: '120', prop: 'categoryName' },
                { label: '主设备名称', width: '80', prop: 'spuMainName' },
                { label: '源头赋码标识', width: '90', prop: 'ifSourceName' },
                { label: '计量单位', width: '60', prop: 'unit' },
                { label: '设计数量', width: '60', prop: 'eqAmount' },
                { label: '出库单明细ID', width: '110', prop: 'osDetailId' },
                { label: '出库数量', width: '60', prop: 'osAmount' },
                { label: '供应商名称', width: '110', prop: 'providerName' },
                { label: '建设子专业', width: '80', prop: 'subSpec' },
                { label: '绑定数量', width: '60', prop: 'boundNum' }
            ],
            keyCode: 'categoryCode',
            columnArr: [1, 2, 3, 4, 5, 6],
            pageHeight: 332,
            visible: false,
            message: [],
            type: '',
            operate: '',
            showResLabel: false,
            osDetailIdAndAssetLabelList:[],
            resourceList:[],
            indexTemp:0,
            subIndexTemp:0,
            selectItem:{},
            multipleData:[],
            osAmount:'',//当前点击单元格的出库数量
        }
    },
    computed: {},
    async created() {
        await this.getTableList()
    },
    methods: {
        getBoundArr(data){
          const arr=[];
          if(data.length > 0){
            data.forEach((item)=>{
              arr.push({
                sourceAssetCode:item.sourceAssetCode,
                labelId:item.labelId,
                amount:item.amount,
                subPrjId:this.selectItem.prjId,
                subSpec:this.selectItem.subType,
                bundingId:-1,
                prjCode:this.selectItem.prjCode,
              })
            })
          }
          return arr;
        },
        updateOsDetailList(data){
          this.osDetailIdAndAssetLabelList.forEach((item)=>{
            if(item.osDetailId === this.tableData[this.indexTemp].osDetailId){
              item.assetsLabelList.forEach((subItem)=>{
                if(data.length>0){
                  //无->有
                  let flag=data.some((childItem)=>childItem.sourceAssetCode === subItem.sourceAssetCode)
                  if(flag){
                    subItem.subPrjId=this.selectItem.prjId
                    subItem.subSpec=this.selectItem.subType
                    subItem.bundingId=-1
                    subItem.prjCode=this.selectItem.prjCode
                  }else{
                    this.setSubItem(subItem)
                  }
                }else{
                  //有->无
                  this.setSubItem(subItem)
                }
              })
            }
          })
        },
        setSubItem(subItem){
          if(subItem.subSpec === this.selectItem.subType && subItem.subPrjId === this.selectItem.prjId){
            subItem.subSpec=null
            subItem.bundingId=null
            subItem.prjCode=null
          }
        },
        saveResource(data,bindNum){
          //更新表格数据 this.$refs.customTable.numAdd(sum, item1.subBoundNum)
          this.tableData[this.indexTemp].singlePrjList[this.subIndexTemp].assetsLabelList=this.getBoundArr(data);
          this.tableData[this.indexTemp].singlePrjList[this.subIndexTemp].subBoundNum= this.$refs.resourceModal.getAmountSum(this.getBoundArr(data))+bindNum;
          this.tableData[this.indexTemp].boundNum=this.getNum(this.tableData[this.indexTemp]);
          //更新签码集合数据
          this.updateOsDetailList(data);
        },
        selectResource(item, index,i) {
          //匹配当前需要展示的签码列表  拿到当前点击的单元格数据
          this.indexTemp=index;
          this.subIndexTemp=i;
          this.selectItem=item;
          this.osAmount=this.tableData[index].osAmount;
          this.getResourceList(index,item);
          this.showResLabel = true
        },
        //获取弹窗需要的签码集合，并判断是否禁用
        getResourceList(index,selectItem){
          this.resourceList=[];
          this.multipleData=[];
          const arr= this.osDetailIdAndAssetLabelList.filter(item=>item.osDetailId === this.tableData[index].osDetailId);
          const arr2= arr.length>0 ? arr[0].assetsLabelList :[];
          arr2.forEach((item)=>{
            if (this.getStatusOne(item,selectItem)) {
              this.multipleData.push({...item});
            }
            if(item.subSpec && item.bundingId && this.getStatusTwo(item,selectItem)){
              this.resourceList.push({
                ...item,
                select:false
              })
            }else{
              this.resourceList.push({
                ...item,
                select:true
              })
            }
          })
        },
        getStatusOne(item,selectItem){
          return item.subSpec === selectItem.subType && item.subPrjId === selectItem.prjId && item.bundingId;
        },
        getStatusTwo(item,selectItem){
          return item.subPrjId !== selectItem.prjId || item.subPrjId === selectItem.prjId && item.subSpec !== selectItem.subType;
        },
        getNum(item) {
            let sum = 0
            if (item.singlePrjList && item.singlePrjList.length > 0) {
                item.singlePrjList.forEach((item1) => {
                    if (item1.subBoundNum) {
                        sum = this.$refs.customTable.numAdd(sum, item1.subBoundNum)
                    }
                })
            }
            return sum
        },
        // 获取列表数据
        async getTableList() {
            const params = {
                prjId: this.prjParams.prjId,
                applyType: this.applyType,
                subPrjList: this.prjParams.subPrjList,
                workItemId: this.prjParams.workItemId
            }
            this.osDetailIdAndAssetLabelList = []
            queryOsDetailIdAndAssetLabelList(params).then((res)=>{
              if (+res.code !== 200) {
                this.osDetailIdAndAssetLabelList = []
              }else{
                this.osDetailIdAndAssetLabelList = res.data
              }
            })
            this.tableData = []
            await queryProductInfoList(params).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                if (res.data.length > 0) {
                    res.data.forEach((item) => {
                        this.tableData.push({
                            ...item,
                            boundNum: this.getNum(item)
                        })
                    })
                }
                this.$nextTick(() => {
                    const h = this.$refs.materialTabs.clientHeight
                    this.pageHeight = res.data.length ? h + 130 : 332
                    window.parent.postMessage({ height: this.pageHeight, type: 'materialServiceHeight' }, this.$fixIframeArr())
                    console.log(h, this.pageHeight, 'this.pageHeight-true')
                })
                this.tableDataOld=JSON.parse(JSON.stringify(this.tableData))
                this.$refs.customTable.getSpanArr(this.tableData)
                this.$refs.customTable.getMaterialArr(this.tableData)
            })
        },
        eleSignInput() {
            this.getTableList()
        },
        // 按设计方案进行绑定
        designBind() {
            if (this.tableData.length > 0) {
                const params = {
                    prjId: this.prjParams.parentPrjId,
                    subPrjList: this.prjParams.subPrjList
                }
                updateProductBindingDataByDesign(params).then(res => {
                    if (+res.code !== 200) {
                        return msgInfoEl({
                            type: 'error',
                            message: res.message
                        }, 3000)
                    } else {
                        if(res.message){
                            msgInfoEl({
                                type: 'success',
                                message: res.message
                            }, 3000)
                        }
                        this.checkBindingBefore('101', 'design')
                    }
                })
            } else {
                this.checkBindingBefore('101', 'design')
            }
        },
        // 弱校验
        checkBindingBefore(type, operate) {
            this.type = type
            this.operate = operate
            const params = {
                subPrjList: this.prjParams.subPrjList,
                operType: type // 101监理，201项目管理
            }
            // 成功之后，调用弱校验接口
            optionalConfirmProductBindingBefore(params).then((res) => {
                if (+res.code === 200) {
                    this.confirmProductBindingBefore(this.type, this.operate)
                } else {
                    this.message = []
                    this.message.push(res.message)
                    this.visible = true
                }
            })
        },
        changeMsg(status) {
            this.visible = false
            if (status) {
                this.confirmProductBindingBefore(this.type, this.operate)
            } else {
                this.getTableList()
            }
        },
        // 强检验
        confirmProductBindingBefore(type, operate) {
            const params = {
                subPrjList: this.prjParams.subPrjList,
                operType: type // 101监理，201项目管理
            }
            confirmProductBindingBefore(params).then((res) => {
                // 不管成功失败刷新列表
                this.getTableList()
                if (+res.code !== 200) {
                    return msgInfoEl({
                        type: 'error',
                        message: res.message
                    }, 3000)
                } else {
                    return msgInfoEl({
                        type: 'success',
                        message: operate === 'design' ? '按设计方案绑定结果成功！' : '确认物资绑定结果成功！'
                    }, 3000)
                }
            })
        },
        getSendArray(item,index){
          const arr = []
          if (item.singlePrjList && item.singlePrjList.length > 0) {
            item.singlePrjList.forEach((subItem,i) => {
              this.prjParams.subPrjList.forEach(v => {
                if (v === subItem.prjId && subItem.ifAppEdit === '1') {
                  if(item.assetsLabelList && item.assetsLabelList.length > 0){
                    arr.push({
                      prjId: subItem.prjId,
                      prjCode: subItem.prjCode,
                      parentPrjId: this.prjParams.parentPrjId,
                      currentAmount: subItem.subBoundNum,
                      oldAssetsLabelList:this.tableDataOld[index].singlePrjList[i].assetsLabelList,
                      newAssetsLabelList:subItem.assetsLabelList,
                    })
                  }else{
                    arr.push({
                      prjId: subItem.prjId,
                      prjCode: subItem.prjCode,
                      parentPrjId: this.prjParams.parentPrjId,
                      currentAmount: subItem.subBoundNum
                    })
                  }
                }
              })
            })
          }
          return arr;
        },
        getSendParams(){
          const params = []
          this.tableData.forEach((item, index) => {
            const arr=this.getSendArray(item,index);
            if (arr.length > 0) {
              params.push({
                serialNum: index + 1,
                osDetailId: item.osDetailId,
                subType: item.subType,
                categoryCode: item.categoryCode,
                productBindingInfo: arr
              })
            }
          })
          return params;
        },
        // 确认绑定结果，父组件调用
        handleSend() {
            if (this.isEdit) {
                const params=this.getSendParams();
                console.log(params)
                if (this.tableData.length > 0 && params.length > 0) {
                    // 确认绑定结果
                    saveProductBindingData(params).then((res) => {
                        if (+res.code !== 200) {
                            return Promise.reject(res)
                        }
                        this.checkBindingBefore('101', 'confirm')
                    })
                } else {
                    // 如果没有数据，直接调校验接口
                    this.checkBindingBefore('101', 'confirm')
                }
            } else {
                this.checkBindingBefore('201', 'confirm')
            }
        },
        // 取消确认，父组件调用
        handleCancel() {
            const params = {
                subPrjList: this.prjParams.subPrjList,
                type: '201', // 101监理，201项目管理
                state: '0',
                productType: '0'
            }
            batchUpdateAccState(params).then((res) => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                msgInfoEl({
                    type: 'success',
                    message: '取消确认成功！'
                }, 3000)
            })
        }
    }

}
</script>

<style scoped lang="scss">

</style>
